#!/bin/bash

# RTZL AI Web Docker 部署脚本
# 作者：AI Assistant
# 创建时间：$(date)

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_step() {
    echo -e "${BLUE}🔧 $1${NC}"
}

# 检查系统要求
check_requirements() {
    print_step "检查系统要求..."
    
    # 检查 Docker
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        echo "安装指南：https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    # 检查 Docker Compose
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        print_error "Docker Compose 未安装，请先安装 Docker Compose"
        echo "安装指南：https://docs.docker.com/compose/install/"
        exit 1
    fi
    
    # 检查 Docker 服务是否运行
    if ! docker info &> /dev/null; then
        print_error "Docker 服务未运行，请启动 Docker 服务"
        exit 1
    fi
    
    print_success "系统要求检查通过"
}

# 设置环境变量
setup_environment() {
    print_step "设置环境变量..."
    
    # 后端环境变量
    if [ ! -f "backend/.env" ]; then
        if [ -f "env.example" ]; then
            print_info "创建后端环境变量文件..."
            cp env.example backend/.env
            print_warning "请编辑 backend/.env 文件，填入正确的配置信息"
            print_warning "特别是API密钥：OPENAI_API_KEY, DASHSCOPE_API_KEY 等"
        else
            print_error "找不到环境变量示例文件 env.example"
            exit 1
        fi
    fi
    
    # 前端环境变量
    if [ ! -f "frontend/.env" ]; then
        if [ -f "frontend/env.example" ]; then
            print_info "创建前端环境变量文件..."
            cp frontend/env.example frontend/.env
        else
            print_warning "找不到前端环境变量示例文件，使用默认配置"
        fi
    fi
    
    print_success "环境变量设置完成"
}

# 创建必要的目录
create_directories() {
    print_step "创建必要的目录..."
    
    # 后端目录
    mkdir -p backend/uploads
    mkdir -p backend/logs
    mkdir -p backend/catch
    
    # 设置权限
    if [[ "$OSTYPE" != "msys" && "$OSTYPE" != "win32" ]]; then
        chmod 755 backend/uploads
        chmod 755 backend/logs
        chmod 755 backend/catch
    fi
    
    print_success "目录创建完成"
}

# 选择部署模式
select_deployment_mode() {
    print_step "选择部署模式..."
    
    echo "请选择部署模式："
    echo "1) 仅后端服务"
    echo "2) 后端 + 前端 (完整部署)"
    echo "3) 开发模式 (包含调试功能)"
    
    read -p "请输入选择 (1-3): " mode
    
    case $mode in
        1)
            DEPLOYMENT_MODE="backend"
            print_info "选择：仅后端服务"
            ;;
        2)
            DEPLOYMENT_MODE="full"
            print_info "选择：完整部署"
            ;;
        3)
            DEPLOYMENT_MODE="development"
            print_info "选择：开发模式"
            ;;
        *)
            print_warning "无效选择，使用默认模式：完整部署"
            DEPLOYMENT_MODE="full"
            ;;
    esac
}

# 停止现有服务
stop_existing_services() {
    print_step "停止现有服务..."
    
    if docker-compose ps -q | grep -q .; then
        docker-compose down --remove-orphans
        print_success "现有服务已停止"
    else
        print_info "没有运行中的服务"
    fi
}

# 构建和启动服务
build_and_start_services() {
    print_step "构建和启动服务..."
    
    # 构建镜像
    case $DEPLOYMENT_MODE in
        "backend")
            print_info "构建后端服务..."
            docker-compose build --no-cache backend mysql redis
            print_info "启动后端服务..."
            docker-compose up -d backend mysql redis
            ;;
        "full")
            print_info "构建所有服务..."
            docker-compose build --no-cache
            print_info "启动所有服务..."
            docker-compose up -d
            ;;
        "development")
            print_info "构建开发环境..."
            docker-compose build --no-cache
            print_info "启动开发环境..."
            docker-compose up -d
            ;;
    esac
    
    print_success "服务构建和启动完成"
}

# 等待服务启动
wait_for_services() {
    print_step "等待服务启动..."
    
    # 等待 MySQL
    print_info "等待 MySQL 数据库启动..."
    for i in {1..30}; do
        if docker-compose exec -T mysql mysqladmin ping -h localhost --silent > /dev/null 2>&1; then
            print_success "MySQL 数据库启动成功"
            break
        else
            print_info "等待 MySQL 启动... ($i/30)"
            sleep 2
        fi
        
        if [ $i -eq 30 ]; then
            print_error "MySQL 启动超时"
            docker-compose logs mysql
            exit 1
        fi
    done
    
    # 等待 Redis
    print_info "等待 Redis 缓存启动..."
    for i in {1..15}; do
        if docker-compose exec -T redis redis-cli ping > /dev/null 2>&1; then
            print_success "Redis 缓存启动成功"
            break
        else
            print_info "等待 Redis 启动... ($i/15)"
            sleep 2
        fi
        
        if [ $i -eq 15 ]; then
            print_error "Redis 启动超时"
            docker-compose logs redis
            exit 1
        fi
    done
    
    # 等待后端服务
    print_info "等待后端服务启动..."
    for i in {1..60}; do
        if curl -f http://localhost:8800/health > /dev/null 2>&1; then
            print_success "后端服务启动成功"
            break
        else
            print_info "等待后端服务启动... ($i/60)"
            sleep 2
        fi
        
        if [ $i -eq 60 ]; then
            print_error "后端服务启动超时，请检查日志："
            echo "docker-compose logs backend"
            exit 1
        fi
    done
    
    # 如果包含前端，等待前端服务
    if [[ $DEPLOYMENT_MODE == "full" || $DEPLOYMENT_MODE == "development" ]]; then
        print_info "等待前端服务启动..."
        for i in {1..30}; do
            if curl -f http://localhost:3000/health > /dev/null 2>&1; then
                print_success "前端服务启动成功"
                break
            else
                print_info "等待前端服务启动... ($i/30)"
                sleep 2
            fi
            
            if [ $i -eq 30 ]; then
                print_warning "前端服务启动超时，但后端服务正常"
                break
            fi
        done
    fi
}

# 显示部署结果
show_deployment_result() {
    print_step "部署结果..."
    
    echo ""
    print_success "🎉 部署完成！"
    echo ""
    
    print_info "📊 服务访问地址："
    echo "   后端API: http://localhost:8800"
    echo "   API文档: http://localhost:8800/docs"
    echo "   健康检查: http://localhost:8800/health"
    
    if [[ $DEPLOYMENT_MODE == "full" || $DEPLOYMENT_MODE == "development" ]]; then
        echo "   前端界面: http://localhost:3000"
    fi
    
    echo ""
    print_info "🔧 常用命令："
    echo "   查看日志: docker-compose logs -f"
    echo "   查看特定服务日志: docker-compose logs -f backend"
    echo "   重启服务: docker-compose restart"
    echo "   停止服务: docker-compose down"
    echo "   查看状态: docker-compose ps"
    echo ""
    
    print_info "📝 如果遇到问题，请检查："
    echo "   1. env.example 和 backend/.env 文件中的配置是否正确"
    echo "   2. API密钥是否已正确配置"
    echo "   3. 端口是否被占用"
    echo "   4. 网络连接是否正常"
    echo ""
    
    print_info "📋 服务状态："
    docker-compose ps
}

# 主函数
main() {
    echo "🚀 开始部署 RTZL AI Web..."
    echo ""
    
    check_requirements
    setup_environment
    create_directories
    select_deployment_mode
    
    # 询问是否继续
    echo ""
    print_warning "请确认您已经："
    echo "1. 编辑了 backend/.env 文件"
    echo "2. 填入了正确的API密钥"
    echo "3. 配置了数据库连接信息"
    echo ""
    
    read -p "确认继续部署？(y/N): " confirm
    if [[ ! $confirm =~ ^[Yy]$ ]]; then
        print_info "部署已取消"
        exit 0
    fi
    
    stop_existing_services
    build_and_start_services
    wait_for_services
    show_deployment_result
}

# 运行主函数
main 